/*-------------------------------------------------------------------------

***************** Modification History ***********************************
   @doc
   @module init.c - Application initialization functions |
   @end

$Log: /SoftPay (1.3d)/SPK2SIM/Source/Main/init.c $
 *
 * 2     8/25/00 12:27p Nick_t1
 *
 * 1     8/24/00 5:34p Nick_t1
**************************************************************************

   Copyright (C) 1999 by VeriFone, Inc.

   All rights reserved.  No part of this software may be reproduced,
   transmitted, transcribed, stored in a retrieval system, or translated
   into any language or computer language, in any form or by any means,
   electronic, mechanical, magnetic, optical, chemical, manual or otherwise,
   without the prior written permission of VeriFone, Inc.

---------------------------------------------------------------------------*/
#define VSINIT_C

//#include <beetle.h>
//#include <beetleplug.h>

#include <aclconio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <txoinc.h>
#include <svc.h>
#include <aclstr.h>
#include <acldev.h>
#include <message.h>
#include <applidl.h>

#include <project.h>
/** /#define DEBUG_VSINIT*/
#ifdef DEBUG_VSINIT
#define DEBUG_95
#endif

#include <define.h>
#include <transact.h>
#include <print.h>
#include <init.h>
#include <accum.h>
#include <pbatch.h>
#include <gds.h>
#include <msg.h>
#include <msgfuncs.h>
#include <pbatch.h>
#include <card.h>
#include <ui.h>
#include <logo.h>
#include <menufunc.h>
#include <modemmsg.h>
#include <modem.h>
#include <comm.h>
#include <oper.h>
#include <fct.h>
#include <lct.h>
//#include <lct1.h>
#include <tct.h>
#include <pct.h>
#include <hdt.h>
#include <opt.h>
#include <cdt.h>
#include <tblutil.h>
#include <confio.h>
#include <table.h>
#include <payment.h>
#include <pinpad.h>
#include <isosizes.h>
#include <ist.h>
#include <isoutl.h>
#include <piputl.h>
#include <protfunc.h>
#include <spdebug.h>
#include <operate.h>

#include <ztconf.h>
#include <test.h>
#include <pcheck.h>
#include <date.h>
#include <ppicge.h>
#include <dct.h>
#include <rcptcmpt.h>
#include <prtfuncs.h>
#include <pfr.h>
#include <clerk.h>
#include <pcr600.h>
#include <packet.h>
#include <iso8.h>
#include <dualcur.h>
#include <pfr.h>

#include <sdt.h>
#include <shift.h>
#include <codesec.h>
#include <pcounter.h>
#include <logsys.h>
#include <tmadef.h>
#ifdef HAND_HELD_DEFINED
#include <handheld.h>
#endif /* HAND_HELD_DEFINED */
#include <mdmdefs.h>

#ifdef SPDDIAL_DEFINED
#include <sdl.h>
#endif

#ifdef ICC_DEFINED
#include <libvoy.h>
#endif

#ifdef EMV_MODULE
#include <emvfuncs.h>
#endif
#ifdef VXEMVAPP
/* Nothing need to include here at this moment */
/* #include <vxemvap.h> */
#endif

#ifdef FLEET_DEFINED
#include <fleet.h>
#endif

int hCardReader;
int hICC1Reader;        /* Chip Card reader handle  */
int hICC2Reader;        /* Chip Card reader handle  */
int remoteTaskID;
int remotePipe;
int spipe;

int (*pinModuleInitFuncs[])(void) =
{
#ifdef PET_DEFINED
inAddProtocolFunctions,         /* Adds the functions used in the protocol table */
#endif

#ifdef ACCUM_DEFINED
inAddAccumFunctions,            /* Adds the ACCUM module functions */
#endif

#ifdef BATCH_DEFINED
inAddBatchFunctions,            /* Adds the BATCH module functions */
#endif

#ifdef CARD_DEFINED
inAddCardFunctions,             /* Adds the CARD module functions */
#endif

#ifdef CLERK_DEFINED
inAddClerkFunctions, ???
#endif

#ifdef SHIFT_DEFINED
inAddShiftFunctions, ???
#endif


#ifdef FORMS_MODULE
inAddFormFunctions,             /* Adds the initialisation function for the receipt segment module */
inAddPrintFunctions,
#endif


#ifdef PINPAD_DEFINED
inAddPinPadFunctions,           /* Adds the PINPad module functions */
#endif

#ifdef DUAL_CURRENCY_DEFINED
inAddDualCurFunctions,  ???
#endif

#ifdef  CHECK_DEFINED               /* Adds the CR600 module functions */
inAddCheckFunctions,   ???
#endif

#ifdef  CR600_DEFINED               /* Adds the CR600 module functions */
inAddCR600Functions,  ???
#endif

//#ifdef PAYMENT_DEFINED              /* Adds the Payments module functions */
//inAddPaymentFunctions,  //
//#endif

#ifdef PIP_DEFINED
inAddPIPISOFunctions,           /* Adds the PIPISO module functions */
inAddPIPFunctions,              /* Adds the PIP module functions */
#endif

#ifdef ISO8583_DEFINED
inAddISO8583Functions,    ???      /* Adds the ISO 8583 module functions */
inAddISO8583ProtFunctions,      /* Adds the ISO 8583 module functions */
inInitializeISO8583Frame,       /* Initializes the ISO8583 Frame */
#endif /* ISO8583_DEFINED */

#ifdef COUNTER_DEFINED
inAddCounterFunctions,   ???        /* Adds the Counter module functions */
#endif /* COUNTER */

#ifdef SPDDIAL_DEFINED
inAddSDFunctions,        ???         /* Adds the SpeedDial module functions */
#endif

#ifdef EMV_MODULE
inAddEMVFunctions,       ???       /* Adds the EMV module functions */
#endif

#ifdef FLEET_DEFINED
inAddFleetFunctions,   ???
#endif

NULL_CH                         /* Must remain at the end of the array */
};

/*-------------------------------------------------------------------------
    Function :  inSelectTemplateFile()
    Description :
    Parameters :
    Returns :
    Notes :
--------------------------------------------------------------------------*/
extern int inImamSetDisplayType(void);
int inSelectTemplateFile(PRINTER_OBJECT* obPrinter) {
    char szTemplateFileName[FILENAME_SIZE + 1];
    char szTemplateFileSuffix[TPL_FILE_SUFFIX_SIZE + 1];

    /** /pdebug (("--inSelectTemplateFile--"));*/

    memset(szTemplateFileName, '\0', sizeof(szTemplateFileSuffix));

    switch (srPtrProps[obPrinter->inType].inColumnType) {
    case COLUMN_TYPE_MULTIPLE:
        p350LinesPerInch(inGetP350LinesPerInch());
        p350ColumnMode(inGetP350ColMode());
        switch (inGetP350ColMode()) {
        case COLUMN_TYPE_24:
            strcpy(szTemplateFileSuffix, "24");
            break;
        case COLUMN_TYPE_32:
            strcpy(szTemplateFileSuffix, "32");
            break;
        case COLUMN_TYPE_42:
            strcpy(szTemplateFileSuffix, "42");
            break;
        }
        break;

    case COLUMN_TYPE_32:
        strcpy(szTemplateFileSuffix, "32");
        break;

    case COLUMN_TYPE_24:
        strcpy(szTemplateFileSuffix, "24");
        break;

    default:
        strcpy(szTemplateFileSuffix, "42");
        break;
    }

    strcat(szTemplateFileName, szTemplateFileSuffix);
    strcat(szTemplateFileName, ".frm");

    if (inSetLCTTemplateSuffix(szTemplateFileName) != VS_SUCCESS)
        return (VS_ERR);

    return (VS_SUCCESS);
}

/*-------------------------------------------------------------------------
    Function :      lnApplInit
    Description :   Application initialization function, called from
                    inApplColdInit
    Parameters :    void
    Returns :       VS_SUCCESS, or error index.
    Notes :
--------------------------------------------------------------------------*/

long lnApplInit() {
    int inElement = 0;
    TRANSACTION_OBJECT obTran,
    * pobTran;
    char e[20];
    int inResult;

    /* CODE SECURITY CHECK CALLED HERE */
    CHECK_CODES(e);

    /* Initialise the PFR logging mechanism to no logging */
#ifdef EXTERN_DEBUG
    LOG_INIT("SOFTPAY", LOGSYS_COMM, 0xFFFFFFFFL);
#else
    LOG_INIT("SOFTPAY", LOGSYS_NONE, 0L);
#endif
    /** /pdebug(("--lnApplInit--"));*/

    memset((char *) &obTran, 0x00, sizeof(TRANSACTION_OBJECT));
    pobTran = &obTran;

	LOG_PRINTFF((0x08L, "vdInitGDS..."));
    vdInitGDS();

    /*
     *      Initialize Display
     *          - Load Terminal Configuration Table
     *          - Load default language for messages
     */
	LOG_PRINTFF((0x08L, "inLoad TCT, PCT, LCT..."));
    if (inLoadTCTRec(0) != VS_SUCCESS)
        return (TCT_ERR_MSG21);

    if (inLoadPCTRec(0) != VS_SUCCESS)
        return (PCT_ERR_MSG);

    if (inGetDefaultLCT() != VS_SUCCESS)
        return (LCT_ERR_MSG);

    /*
     *      Initialize the function table flexi record
     */
	LOG_PRINTFF((0x08L, "inInitializeFunctionRecord..."));
    if (inInitializeFunctionRecord() != VS_SUCCESS)
    {
		LOG_PRINTFF((0x08L, "inInitializeFunctionRecord - FAIL"));
        return (RECORD_INIT_ERR_MSG21);
	}
	
	inImamSetDisplayType();

	LOG_PRINTFF((0x08L, "vdInitDisplay()..."));
    vdInitDisplay();

    /*
     *      Run module initialization functions
     */
    inElement = 0;
    while (pinModuleInitFuncs[inElement] != NULL_CH) {
		LOG_PRINTFF((0x08L, "pinModuleInitFuncs[%d]()...", inElement));
        if (pinModuleInitFuncs[inElement]() == VS_ERR)
        {
            return (RECORD_INIT_ERR_MSG21);
		}
        ++inElement;
    }

    /*
     *      Run handheld initialization functions
     */
#ifdef HAND_HELD_DEFINED
    if (srGDS.fHandHeld)
        inAddHandHeldFlowFunctions();
#endif /* HAND_HELD_DEFINED */
    /*
     *      Run custom initialization functions
     */
    inElement = 0;
    while (pvdCustomInitFuncs[inElement] != NULL_CH) {
		LOG_PRINTFF((0x08L, "pvdCustomInitFuncs[%d]()...", inElement));
        pvdCustomInitFuncs[inElement]();
        ++inElement;
    }

    /*
     *      Process Function Control Table
     */
	LOG_PRINTFF((0x08L, "inProcessFCT..."));
    inProcessFCT(pobTran);

    /*
     *      Display SoftPay logo and copyright information
     */
	LOG_PRINTFF((0x08L, "inDisplayAtInit..."));
    inDisplayAtInit(pobTran);

	LOG_PRINTFF((0x08L, "pstGetSet_pobTran..."));
    pstGetSet_pobTran(&obTran, 1, &inResult);
    if (inResult == VS_ERR)
        return VS_ERR;

    /*
     *      Run Initialization Operation
     */
	LOG_PRINTFF((0x08L, "COLD_INIT_OPERATION..."));
    if (inRunOperation(pobTran, COLD_INIT_OPERATION) != VS_SUCCESS)
    {
        return(RECORD_INIT_ERR_MSG21);
	}
    pstGetSet_pobTran(&obTran, 2, &inResult);
	LOG_PRINTFF((0x08L, "COLD_INIT_OPERATION...SUCCESS"));
    /* ====> CBS 10-20-99 Add Idle loop timer setting initialization    */
    /* May want to make these values user configurable thru Config.sys  */
    /* variables. if so, activate this area of code and add the values  */
    /* to Config.sys.                                                   */ {
        long lnIdle = 250L,
        lnSlow = 300L,
        lnFast = 100L,
        lnCanc = 50L;

#if 0
        if (get_env ("#TMIDLE", szBuffer, 3) > 0)
            lnIdle = atol(szBuffer);
        if (get_env ("#TMSLOW", szBuffer, 3) > 0)
            lnSlow = atol(szBuffer);
        if (get_env ("#TMFAST", szBuffer, 3) > 0)
            lnFast = atol(szBuffer);
        if (get_env ("#TMCANC", szBuffer, 3) > 0)
            lnCanc = atol(szBuffer);
    #endif

        appl_idle_set_idle_loop_time(lnIdle);
        appl_idle_set_slow_poll_time(lnSlow);
        appl_idle_set_fast_poll_time(lnFast);
        appl_idle_set_cancel_poll_time(lnCanc);
    }

    /* Initialise the TMA functions */
#ifdef TMA_DEFINED
    inAddTMAFunctions();
#endif
    /* Set up the power failure recovery functions */
    inAddPFRFunctions();
    //#ifdef DIAL_TASK_DEFINED
#if 1

    vdInitializeSyncDialTask();

#endif /* DIAL_TASK_DEFINED */
    /* Run the power failure function associated with the last PFR state */
    inPFRExecute();
    /* We ALWAYS return to an idle state after the above */
    shSetPFRState(pobTran, PFR_IDLE_STATE, 0, 0, //dont store the transaction object
                        NULL);

#ifdef TMA_DEFINED
    vdInitMonitoredItemDataFile();
#endif
    vdSetMenuFont();

    return (VS_SUCCESS);
} /* End of lnApplInit () */

/*-------------------------------------------------------------------------
    Function :      inApplColdInit
    Description :   Application initialization function, called from
                    cold_boot
    Parameters :    void
    Returns :
    Notes :
--------------------------------------------------------------------------*/

int inApplColdInit() {
    long lnMessageIndex;

    disable_hot_key();			//meca 20040901 -- to disable the hot_key while softpay is initiating

    hCardReader = open(DEV_CARD, O_RDWR);
    //  hCardReader = open("/dev/console", O_RDWR);

    lnMessageIndex = lnApplInit();
    if (lnMessageIndex != VS_SUCCESS) {
        vdDisplayMessageFromFile(lnMessageIndex, WARNING_MSG);
        pause(100);
        clrscr();
        SVC_RESTART("");
    }
    vdFlushKeyboardBuffer();
    clrscr();
    /* pj1  remove forced logon */
    vdInitMenus();

    enable_hot_key();			//meca 20040901 -- to enable the hot_key after initiating the softpay

    return(0);
}

int inInitTerminalBeep(TRANSACTION_OBJECT* pobTran) {
    /*
     *      Set terminal beep on/off
     */
    key_beeps((short) fGetTerminalBeep());

    return (VS_SUCCESS);
}

int inAutoSettle(TRANSACTION_OBJECT* pobTran) {
    vdSGAutoSettle(VS_FALSE);

    return (VS_SUCCESS);
}

int inMemoryCheck(TRANSACTION_OBJECT* pobTran) {
    long lnAvailSz;

    vdDisplayMessageFromFile(MEMORY_CHECK_MSG21, STATUS_MSG);
    if (fMemAvail(&lnAvailSz) != VS_TRUE)
        vdDisplayMessageFromFile(NO_MEM_ERR_MSG, ERROR_MSG);

    return (VS_SUCCESS);
}

//#ifdef DIAL_TASK_DEFINED
#if 1

void vdInitializeSyncDialTask() {
    int inLocalTaskId = get_task_id();
    char arguments[100];
    int inOwnerTaskId = 0xFF;
    char szDevName[DEVICE_NAME_SIZE];

    /** /pdebug(("--vdInitializeSyncDialTask--"));*/

    remotePipe = 0;
    spipe = 0;

    /* OPen the pipe */
    spipe = open(SOFTPAY_PIPE_ID, 0);       // Open primary task PIPE
    /** / pdebug(("--OPened the pipe--"));*/
    pipe_init_msg(spipe, 3);            // Initalize PIP (O/S call)
    /** / pdebug(("--inited pipe--"));*/

    /* The remote must know the local task ID
       Send task ID of primary task as arguments to secondary task */

    sprintf(arguments, "%d%c", inLocalTaskId, 0);
    pdebug(("argument = %s", arguments));

    remoteTaskID = run("F:DIALER.OUT", arguments);
     pdebug(("remoteTaskID = %d", remoteTaskID));
    if (remoteTaskID == -1)
        vdDisplayMessageFromFile(SYSTEM_ERR, WARNING_MSG);
    SVC_WAIT(80);

    /* Get the remote pipe handle
       Get PIPE handle of the secondary task */
    MEMCLR(szDevName, DEVICE_NAME_SIZE);
    strcpy(szDevName, DIALER_PIPE_ID);

    /** / pdebug(("DevName", szDevName));*/
    remotePipe = get_owner(szDevName, &inOwnerTaskId);

    /* Send a pipe message */
    //kv1 debug - 7/11/2001
    pipe_connect(spipe, remotePipe); // connect pri & sec pipes
}

#endif /* DIAL_TASK_DEFINED */


int INIT_CODE_CHECK(char* a,char* b,short * c,char* d,unsigned char* e) {
    GET_VER(a, b, c, d, e);
    return 1;
}



#undef VSINIT_C

